<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label=" 计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入 计划名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label=" 发货方" prop="sendoutCompany">-->
<!--        <el-input-->
<!--          v-model="queryParams.sendoutCompany"-->
<!--          placeholder="请输入 发货方"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label=" 客户" prop="receiveCompany">
        <el-input
          v-model="queryParams.receiveCompany"
          placeholder="请输入 客户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 车牌号" prop="licensePlate">
        <el-input
          v-model="queryParams.licensePlate"
          placeholder="请输入 车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 身份证号" prop="driverIdCard">
        <el-input
          v-model="queryParams.driverIdCard"
          placeholder="请输入 司机身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" 运单状态" prop="waybillState">
        <el-select v-model="queryParams.waybillState" placeholder="请选择 运单状态" clearable>
          <el-option
            v-for="dict in dict.type.waybill_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="派车时间">
        <el-date-picker
          v-model="daterangeDispatchtime"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label=" 货物名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入 货物名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:waybills:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:waybills:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:waybills:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:waybills:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleSignStateChange"
          v-hasPermi="['system:waybills:signStateChange']"
        >签到</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="waybillsList" @selection-change="handleSelectionChange" @row-dblclick="handleRowDblClick">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>

      <el-table-column label="运单编码" align="center" prop="number" />
      <el-table-column label="计划名称" align="center" prop="planName" />
<!--      <el-table-column label="发货方" align="center" prop="sendoutCompany" />-->
      <el-table-column label="客户" align="center" prop="receiveCompany" />
      <el-table-column label="车牌号" align="center" prop="licensePlate" width="100"/>
      <el-table-column label="司机姓名" align="center" prop="driverName" />
      <el-table-column label="身份证号" align="center" prop="driverIdCard" />
      <!--      <el-table-column label=" 审核状态" align="center" prop="checkState" >-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.check_status" :value="scope.row.checkState"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="运单状态" align="center" prop="waybillState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.waybill_state" :value="scope.row.waybillState"/>
        </template>
      </el-table-column>
      <el-table-column label="派车时间" align="center" prop="dispatchtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dispatchtime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签到状态" align="center" prop="signinState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.signin_state" :value="scope.row.signinState"/>
        </template>
      </el-table-column>
      <el-table-column label="签到时间" align="center" prop="signintime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signintime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="stockName" />
      <el-table-column label="货物名称" align="center" prop="itemName" />
      <el-table-column label="货物规格" align="center" prop="itemModel" />
      <el-table-column label="货物价格" align="center" prop="itemPrice" />
      <el-table-column label="皮重" align="center" prop="p" />
      <el-table-column label="毛重" align="center" prop="m" />
      <el-table-column label="净重" align="center" prop="j" />
      <el-table-column label="结算金额" align="center" prop="settlementAmount" />
      <el-table-column label="皮重时间" align="center" prop="ptime" />
      <el-table-column label="毛重时间" align="center" prop="mtime" />
      <el-table-column label="完成时间" align="center" prop="finishtime" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="创建用户名" align="center" prop="createUserName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:waybills:edit']"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:waybills:remove']"-->
<!--          >删除</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleWeighing(scope.row)"
            v-hasPermi="['system:waybills:remove']"
          >称重</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="showRebackDialog(scope.row)"
            v-hasPermi="['system:waybills:rebackState']"
          >回退</el-button>
        </template>
      </el-table-column>
    </el-table>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label=" 计划id" prop="planId">-->
<!--          <el-input v-model="form.planId" placeholder="请输入 计划id" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label=" 计划编码" prop="planNumber">-->
<!--          <el-input v-model="form.planNumber" placeholder="请输入 计划编码" />-->
<!--        </el-form-item>-->
        <el-form-item label=" 计划名称" prop="planName">
          <el-select clearable v-model="form.planId" placeholder="请选择计划" filterable  @change="handlePlanChange">
            <el-option
              v-for="item in planNameOptions"
              :key="item.planId"
              :label="item.planName"
              :value="item.planId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" 货物名称" prop="itemName">
          <el-input v-model="form.itemName" :disabled="true"/>
        </el-form-item>
        <el-form-item label=" 货物规格" prop="itemModel">
          <el-input v-model="form.itemModel"  :disabled="true"/>
        </el-form-item>
        <el-form-item label=" 货物价格" prop="itemPrice">
          <el-input v-model="form.itemPrice"  :disabled="true"/>
        </el-form-item>
<!--        <el-form-item label=" 发货方" prop="sendoutCompany">-->
<!--          <el-input v-model="form.sendoutCompany" :disabled="true"/>-->
<!--        </el-form-item>-->
        <el-form-item label=" 客户" prop="receiveCompany">
          <el-input v-model="form.receiveCompany" :disabled="true"/>
        </el-form-item>
        <el-form-item label=" 车牌号" prop="licensePlate">
          <el-select clearable v-model="form.carId" placeholder="请选择车牌号" filterable  @change="handleCarChange">
            <el-option
              v-for="item in carOptions"
              :key="item.id"
              :label="item.licensePlate"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label=" 司机id" prop="driverId">-->
<!--          <el-input v-model="form.driverId" placeholder="请输入 司机id" />-->
<!--        </el-form-item>-->
        <el-form-item label=" 司机姓名" prop="driverName">
          <el-input v-model="form.driverName" :disabled="true" />
        </el-form-item>
        <el-form-item label="身份证号" prop="driverIdCard">
          <el-input v-model="form.driverIdCard" :disabled="true" />
        </el-form-item>
        <el-form-item label="仓库" prop="stockId">
          <el-select v-model="form.stockId" placeholder="请选择仓库" clearable filterable @change="handleStockChange">
            <el-option
              v-for="driver in this.stocksInfoList"
              :key="driver.id"
              :label="driver.name"
              :value="driver.id"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 回退状态弹窗 -->
    <el-dialog title="回退运单步骤" :visible.sync="rebackDialogVisible" width="400px" append-to-body>
      <el-form ref="rebackForm" :model="rebackForm" :rules="rebackRules" label-width="80px">
        <el-form-item label="回退状态" prop="yyskState">
          <el-select v-model="rebackForm.yyskState" placeholder="请选择回退状态" style="width: 100%">
            <el-option
              v-for="dict in dict.type.yysk_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rebackDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReback">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listWaybills, getWaybills, delWaybills, addWaybills, updateWaybills,signStateChange,rebackState } from "@/api/system/waybills"
import { getPlanNameOptions } from "@/api/system/salePlan"
import { getCarInfoOptions } from "@/api/system/cars"
import {getStocksInfoList } from "@/api/system/stocks"

export default {
  name: "Waybills",
  dicts: ['waybill_state', 'check_status','signin_state','yysk_state'],
  data() {
    return {

      // 在 data() 的 return 对象中添加以下属性
      rebackDialogVisible: false,
      rebackForm: {
        id: null,
        yyskState: ''
      },
      rebackRules: {
        yyskState: [{ required: true, message: '请选择回退状态', trigger: 'change' }]
      },

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运单表格数据
      waybillsList: [],
      planNameOptions:[],
      carOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //  净重时间范围
      daterangeDispatchtime: [],
      stocksInfoList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planName: null,
        sendoutCompany: null,
        receiveCompany: null,
        licensePlate: null,
        driverName: null,
        driverIdCard: null,
        waybillState: null,
        dispatchtime: null,
        itemName: null,
        p: null,
        m: null,
        j: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planName: [
          { required: true, message: '计划 不能为空', trigger: 'blur' },
        ],
        licensePlate: [
          { required: true, message: '车辆信息 不能为空', trigger: 'blur' },
        ],
        stockId: [
          { required: true, message: '仓库 不能为空', trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    this.getList();
    this.getPlanNameOptions(1); // 1 销售类型
    this.getCarOptions();
    this.getStocksList();
  },
  methods: {

    /** 获取仓库列表 */
    getStocksList() {
      // 这里需要替换为实际的API调用
      getStocksInfoList(this.paramName).then(response => {
        this.stocksInfoList = response.rows
      })
    },

    // 显示回退弹窗
    showRebackDialog(row) {
      this.rebackForm.id = row.id;
      this.rebackForm.yyskState = '';
      this.rebackDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.rebackForm.resetFields();
      });
    },

// 提交回退状态
    submitReback() {
      this.$refs.rebackForm.validate(valid => {
        if (valid) {
          const params = {
            id: this.rebackForm.id,
            yyskState: this.rebackForm.yyskState
          };
          // 调用回退状态接口
          rebackState(params).then(response => {
            this.$modal.msgSuccess("回退成功");
            this.rebackDialogVisible = false;
            this.getList(); // 刷新列表
          }).catch(() => {
            this.$modal.msgError("回退失败");
          });
        }
      });
    },


    /** 称重按钮操作 */
      handleWeighing(row) {
        this.$router.push(`/system/waybills/weighting/${row.id}`);
      },

    handleRowDblClick(row) {
      // 双击行时跳转到详情页
      this.$router.push(`/system/waybills/detail/${row.id}`)
    },

    handleCarChange(id) {
        if (id) {
          // 根据选中的车辆ID查找对应的车辆信息
          const selectedGoods = this.carOptions.find(goods => goods.id === id);
          if (selectedGoods) {
            // 获取车辆信息
            this.form.licensePlate = selectedGoods.licensePlate || '';
            this.form.carId = selectedGoods.id || '';
            this.form.driverName = selectedGoods.driver || '';
            this.form.driverId = selectedGoods.driverId || '';
            this.form.driverIdCard = selectedGoods.driverIdCard || '';
          }
        } else {
          // 清空选择时，重置相关字段
          this.form.licensePlate = '';
          this.form.carId = '';
          this.form.driverId = '';
          this.form.driverName = '';
          this.form.driverIdCard = '';
      }
    },

    /** 仓库选择变化处理 */
    handleStockChange(id) {
      if (id) {
        // 根据选中的仓库ID查找对应的仓库信息
        const selectedStock = this.stocksInfoList.find(stock => stock.id === id);
        if (selectedStock) {
          // 同时设置仓库ID和仓库名称
          this.form.stockId = selectedStock.id || '';
          this.form.stockName = selectedStock.name || '';
        }
      } else {
        // 清空选择时，重置相关字段
        this.form.stockId = '';
        this.form.stockName = '';
      }
    },


    /** 获取车辆列表 */
    getCarOptions() {
      // 这里需要替换为实际的API调用
      getCarInfoOptions(this.paramName).then(response => {
        this.carOptions = response.rows
      })
    },


    handlePlanChange(id) {
      if (id) {
        // 根据选中的计划ID查找对应的计划信息
        const selectedGoods = this.planNameOptions.find(goods => goods.planId === id);
        if (selectedGoods) {
          // 设置货物规格（禁用状态）
          this.form.sendoutCompanyId = selectedGoods.sendoutCompanyId || '';
          this.form.receiveCompanyId = selectedGoods.receiveCompanyId || '';
          this.form.sendoutCompany = selectedGoods.sendoutCompany || '';
          this.form.receiveCompany = selectedGoods.receiveCompany || '';
          this.form.itemName = selectedGoods.itemName || '';
          this.form.itemModel = selectedGoods.itemModel || '';
          this.form.itemPrice = selectedGoods.itemPrice || '';
          this.form.itemId = selectedGoods.itemId || '';

          this.form.planId = selectedGoods.planId || '';
          this.form.planNumber = selectedGoods.planNumber || '';
          this.form.planName = selectedGoods.planName || '';

        }
      } else {
        // 清空选择时，重置相关字段
        this.form.sendoutCompanyId =  '';
        this.form.receiveCompanyId =  '';
        this.form.sendoutCompany =  '';
        this.form.receiveCompany = '';

        this.form.planId =  '';
        this.form.planNumber = '';
        this.form.planName = '';
        this.form.itemName = '';
        this.form.itemModel = '';
        this.form.itemPrice = '';
        this.form.itemId = '';
      }
    },



    /** 获取计划列表 */
    getPlanNameOptions(par) {

      var param = {
        type : par,
        name : this.paramName,
      }

      // 这里需要替换为实际的API调用
      getPlanNameOptions(param).then(response => {
        this.planNameOptions = response.rows
      })
    },


/** 查询运单列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeDispatchtime && '' != this.daterangeDispatchtime) {
        this.queryParams.params["beginDispatchtime"] = this.daterangeDispatchtime[0]
        this.queryParams.params["endDispatchtime"] = this.daterangeDispatchtime[1]
      }
      listWaybills(this.queryParams).then(response => {
        this.waybillsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantId: null,
        createTime: null,
        updateTime: null,
        createUserId: null,
        createOrgId: null,
        createUserName: null,
        updateUserId: null,
        updateUserName: null,
        isDelete: null,
        orgId: null,
        createOrgName: null,
        sqare01: null,
        sqare02: null,
        sqare03: null,
        sqare04: null,
        sqare05: null,
        sqare06: null,
        number: null,
        planId: null,
        planNumber: null,
        planName: null,
        contractNumber: null,
        contractName: null,
        type: null,
        sendoutCompany: null,
        receiveCompany: null,
        carrierCompany: null,
        licensePlate: null,
        carType: null,
        driverId: null,
        driverName: null,
        drivertelephone: null,
        driverIdCard: null,
        fwid: null,
        handledby: null,
        handledbyOrg: null,
        reviewerId: null,
        reviewer: null,
        reviewbyOrg: null,
        reviewTime: null,
        checkState: null,
        waybillState: null,
        checkUp: null,
        checkUpBy: null,
        checkUpDate: null,
        businessType: null,
        code: null,
        currentUnit: null,
        dispatchtime: null,
        signinState: null,
        signintime: null,
        fAdmissionTime: null,
        finishtime: null,
        contactId: null,
        handledbyOrgId: null,
        settlementState: null,
        inpassState: null,
        inpasstime: null,
        abnormalState: null,
        sendoutCompanyId: null,
        receiveCompanyId: null,
        transactionAmount: null,
        tradingTime: null,
        repeatPrint: null,
        dispatchdesc: null,
        dispatchBy: null,
        signindesc: null,
        signinBy: null,
        inpassdesc: null,
        inpassBy: null,
        enterdesc: null,
        enterBy: null,
        enterimg: null,
        finishdesc: null,
        finishBy: null,
        finishimg: null,
        carnoColor: null,
        carId: null,
        generatedState: null,
        contractId: null,
        itemId: null,
        itemName: null,
        itemModel: null,
        itemPrice: null,
        priceType: null,
        settlementType: null,
        pickCode: null,
        takeEffect: null,
        fissueqty: null,
        catchweight: null,
        p: null,
        m: null,
        j: null,
        settlementQty: null,
        stockId: null,
        stockName: null,
        settlementPrice: null,
        settlementAmount: null,
        transportPrice: null,
        damageAmount: null,
        dumpType: null,
        dumpOrder: null,
        handlingAmount: null,
        transportAmount: null,
        ptime: null,
        mtime: null,
        printtime: null,
        payState: null,
        itemNumber: null,
        measuringMethod: null,
        packageType: null,
        packageNum: null,
        cube: null,
        actualWeight: null,
        itemType: null,
        mSecond: null,
        mtimeSecond: null,
        pSecond: null,
        ptimeSecond: null,
        jSecond: null,
        jtimeSecond: null,
        pdesc: null,
        pby: null,
        pimg: null,
        mdesc: null,
        mby: null,
        mimg: null,
        mdescSecond: null,
        mbySecond: null,
        mimgSecond: null,
        stockIds: null,
        ratedGrossweight: null,
        ratedTareweight: null,
        waybillUuid: null,
        notInpassState: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDispatchtime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getPlanNameOptions(1); // 1 销售类型
      this.getCarOptions();
      this.getStocksList();
      this.open = true
      this.title = "添加运单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getPlanNameOptions(1); // 1 销售类型
      this.getCarOptions();
      this.getStocksList();
      const id = row.id || this.ids
      getWaybills(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改运单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWaybills(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addWaybills(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除运单编号为"' + ids + '"的数据项？').then(function() {
        return delWaybills(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    handleSignStateChange() {
      const ids = this.ids
      this.$modal.confirm('是否签到?').then(function() {
        return signStateChange(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("签到成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/waybills/export', {
        ...this.queryParams
      }, `waybills_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
